package com.crm.system.service.impl.productManager;

import com.crm.common.model.DhPageInfo;
import com.crm.common.model.Enum.StatusCodeEnum;
import com.crm.common.util.CommonUtils;
import com.crm.common.util.YearWeeksUtil;
import com.crm.model.entity.productManager.CustomerProduct;
import com.crm.model.entity.sys.UserAccount;
import com.crm.model.qo.productManager.CustomerProductQO;
import com.crm.model.qo.productManager.CustomerProductUpdateQO;
import com.crm.model.vo.productManager.AnalyseFinishOrderProductVO;
import com.crm.model.vo.productManager.CustomerProductUpdateVO;
import com.crm.model.vo.productManager.CustomerProductVO;
import com.crm.model.vo.productManager.ProductAnalyseVO;
import com.crm.redis.RedisPrefix;
import com.crm.redis.mapper.ValueRMapper;
import com.crm.service.productManager.CustomerProductDbService;
import com.crm.service.returnMoney.FinishOrderDBservice;
import com.crm.service.sys.UserAccountDbService;
import com.crm.system.service.productManager.CustomerProductService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.*;

/**
 * @Author yincuimei
 * @Date 2021/1/27 15:39
 */
@Slf4j
@Service
public class CustomerProductServiceImpl implements CustomerProductService{
    @Autowired
    private CustomerProductDbService customerProductDbService;
    @Autowired
    private FinishOrderDBservice finishOrderDBservice;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private UserAccountDbService userAccountDbService;

    /**
     * 产品管理--非会员产品列表分页信息
     * @param customerProductQO    ---产品列表查询参数
     * @param pageIndex/ pageSize  ---页码、分页大小
     * @param sortName/sortOrder   ---产品列表排序字段及规则
     * @return
     */
    @Override
    public DhPageInfo<CustomerProductVO> selectCustomerProductVOList(CustomerProductQO customerProductQO,Integer pageIndex,Integer pageSize,String sortName,String sortOrder,Integer tag){
        if (pageIndex != null && pageSize != null) {
            PageHelper.startPage(pageIndex, pageSize);
        }

        //增加删除状态查询条件(0:正常;1:已删除)
        customerProductQO.setDeleteStatus((short) StatusCodeEnum.NORMAL_CODE.getState());
        //排序
        StringBuilder order = new StringBuilder();
        if(!StringUtils.isBlank(sortName)&&!StringUtils.isBlank(sortOrder)){
            switch(sortName){
                case "createTm": {
                    order.append("create_tm ").append(sortOrder);//创建时间
                }
                break;
                case "productName": {
                    order.append("product_name ").append(sortOrder);//产品名称
                }
                break;
                case "productTag": {
                    order.append("product_tag ").append(sortOrder);//产品标签
                }
                break;
                case "serviceClassification": {
                    order.append("service_classification ").append(sortOrder);//服务分类
                }
                break;
                case "productUnitPrice": {
                    order.append("product_unit_price ").append(sortOrder);//产品原价
                }
                break;
                case "performanceConversionRatio": {
                    order.append("performance_conversion_ratio ").append(sortOrder);// //业绩汇算比例
                }
                break;
                case "productMemberPrice": {
                    order.append("product_member_price ").append(sortOrder);//产品会员价
                }
                break;
                case "exchangeMethod": {
                    order.append("exchange_method ").append(sortOrder);//兑换方式
                }
                break;
                case "shelfStatus": {
                    order.append("shelf_status ").append(sortOrder);//上架状态：0-待定；1-已上架； 2-已下架
                }
                break;
                case "productOriginalPrice": {
                    order.append("product_original_price ").append(sortOrder);//产品原价
                }
                break;
                default:
                    break;
            }
        }else{
            if(tag!= null && tag == 1) { //管理端
                order.append("shelf_status ").append("desc");//
                order.append(",product_name ").append("asc");
            }
        }
        PageHelper.orderBy(order.toString());
        if(tag!=null && tag == 2) { //用户端
            customerProductQO.setShelfStatus("1");
        }
        if(tag!=null && tag == 0) {
            customerProductQO.setShelfStatus("1");
        }
        List<CustomerProductVO> customerProductVOList = customerProductDbService.selectCustomerProductVOList(customerProductQO,order.toString());
        PageInfo<CustomerProductVO> pageInfo = new PageInfo<CustomerProductVO>(customerProductVOList);
        return new DhPageInfo<CustomerProductVO>(pageInfo, customerProductVOList);
    }

    /**
     * 优惠券页面，为了和会员产品在同一列表展示，统一使用会员产品字段名
     * @param customerProductQO    ---产品列表查询参数
     * @param pageIndex/ pageSize  ---页码、分页大小
     * @param sortName/sortOrder   ---产品列表排序字段及规则
     * @return
     */
    @Override
    public DhPageInfo<Map<String,Object>> selectCustomerProductVOListForCoupon(CustomerProductQO customerProductQO,Integer pageIndex,Integer pageSize,String sortName,String sortOrder,Integer tag){
        if (pageIndex != null && pageSize != null) {
            PageHelper.startPage(pageIndex, pageSize);
        }

        //增加删除状态查询条件(0:正常;1:已删除)
        customerProductQO.setDeleteStatus((short) StatusCodeEnum.NORMAL_CODE.getState());
        //排序
        StringBuilder order = new StringBuilder();
        if(!StringUtils.isBlank(sortName)&&!StringUtils.isBlank(sortOrder)){
            switch(sortName){
                case "createTm": {
                    order.append("create_tm ").append(sortOrder);//创建时间
                }
                break;
                default:
                    break;
            }
        }
        PageHelper.orderBy(order.toString());
        if(tag!=null && tag == 0) {
            customerProductQO.setShelfStatus("1");
        }
        List<Map<String,Object>> customerProductVOList = customerProductDbService.selectCustomerProductVOListForCoupon(customerProductQO,order.toString());
        PageInfo<Map<String,Object>> pageInfo = new PageInfo<Map<String,Object>>(customerProductVOList);
        return new DhPageInfo<Map<String,Object>>(pageInfo, customerProductVOList);
    }

    /**
     * 产品管理--根据产品ID和删除状态查询产品信息(产品编辑)
     * @param customerProductId  ---产品ID
     * @return
     */
    @Override
    public CustomerProductUpdateVO selectCustomerProductUpdateVOById(String customerProductId) {
        CustomerProduct customerProduct = customerProductDbService.selectCustomerProductById(customerProductId,(short)StatusCodeEnum.NORMAL_CODE.getState());
        CustomerProductUpdateVO customerProductUpdateVO = new CustomerProductUpdateVO();
        BeanUtils.copyProperties(customerProduct,customerProductUpdateVO);
        return customerProductUpdateVO;
    }

    /**
     * 产品管理--产品列表(上/下架操作)
     * @param customerProductId   ---产品主键
     * @param shelfStatus         ---上/下架标识(0-待定；1-已上架； 2-已下架)
     * @return
     */
    @Override
    public Boolean updateCustomerProductShelfStatus(String customerProductId, String shelfStatus) {
        UserAccount userAccount = (UserAccount) SecurityUtils.getSubject().getPrincipal();//获取登录人信息
        CustomerProduct customerProduct = new CustomerProduct();
        if(!StringUtils.isBlank(customerProductId) && shelfStatus != null){
            customerProduct.setCustomerProductId(customerProductId);
            customerProduct.setShelfStatus(shelfStatus);
            if("1".equals(shelfStatus)){//上架
                customerProduct.setShelfTime(new Date());//上架时间
                customerProduct.setOffShelfTime(null);
            }else if("2".equals(shelfStatus)){//下架
                customerProduct.setOffShelfTime(new Date());//下架时间
                customerProduct.setShelfTime(null);
            }
        }
        customerProduct.setUpdateTm(new Date());//更新时间
        customerProduct.setUpdatePeopleId(userAccount.getAccountId());//更新人
        return customerProductDbService.updateCustomerProductShelfStatus(customerProduct);
    }

    /**
     * 产品管理--查询产品名称是否已存在
     * @param productName   ---产品名称
     * @return
     */
    @Override
    public Boolean isExistProductName(String productName) {
        return customerProductDbService.isExistProductName(productName,(short)StatusCodeEnum.NORMAL_CODE.getState());
    }

    /**
     * 产品管理--查询产品编码是否已存在
     * @param productCode   ---产品编码
     * @return
     */
    @Override
    public Boolean isExistProductCode(String productCode) {
        return customerProductDbService.isExistProductCode(productCode,(short)StatusCodeEnum.NORMAL_CODE.getState());
    }

    /**
     * 产品管理--查询专题ID是否已存在
     * @param topicId  ---专题ID
     * @return
     */
    @Override
    public Boolean isExistTopicId(Integer topicId) {
        return customerProductDbService.isExistTopicId(topicId,(short)StatusCodeEnum.NORMAL_CODE.getState());
    }

    /**
     * 产品管理--新增产品
     * @param customerProduct  ---产品信息
     * @return
     */
    @Override
    public Boolean insertCustomerProduct(CustomerProduct customerProduct) {
        UserAccount userAccount = (UserAccount) SecurityUtils.getSubject().getPrincipal();//获取登录人信息
        customerProduct.setCustomerProductId(CommonUtils.getGUID());//主键
        customerProduct.setCreateTm(new Date());//创建时间
        customerProduct.setCreatePeopleId(userAccount.getAccountId());//创建人
        customerProduct.setDeleteStatus((short)StatusCodeEnum.NORMAL_CODE.getState());//删除状态
        customerProduct.setShelfStatus("0");//(上/下架状态:待定)
        return customerProductDbService.insertCustomerProduct(customerProduct);
    }

    /**
     * 产品管理--编辑产品
     * @param customerProductUpdateQO  ---产品编辑信息
     * @return
     */
    @Override
    public Boolean updateCustomerProductById(CustomerProductUpdateQO customerProductUpdateQO) {
        UserAccount userAccount = (UserAccount) SecurityUtils.getSubject().getPrincipal();//获取登录人信息
        customerProductUpdateQO.setUpdatePeopleId(userAccount.getAccountId());//更新人ID
        customerProductUpdateQO.setUpdateTm(new Date());//更新时间
        return customerProductDbService.updateCustomerProductById(customerProductUpdateQO);
    }

    @Override
    public List<HashMap> selectProductDropDownList(String productName) {
        List<HashMap> customerProductList = customerProductDbService.selectALLProductDropDownList(productName);
        return customerProductList;
    }

    /**
     * 商机-新增商机-查询所有产品列表
     * @param pageIndex 页码
     * @param pageSize 分页大小
     * @param sortName 排序列名字
     * @param sortOrder 排序规则
     * @param productName 产品名称
     * @return
     */
    @Override
    public DhPageInfo<CustomerProduct> productList(Integer pageIndex,Integer pageSize,String sortName,String sortOrder,String productName,String productCategories) {
        if (pageIndex != null && pageSize != null) {
            PageHelper.startPage(pageIndex, pageSize);
        }

        //排序
        StringBuilder order = new StringBuilder();
        if(!StringUtils.isBlank(sortName)&&!StringUtils.isBlank(sortOrder)){
            switch(sortName){
                case "createTm":
                {
                    order.append("create_tm ").append(sortOrder);//创建时间
                }
                break;
                default:
                    break;
            }
        }
        List<CustomerProduct> list = customerProductDbService.productList(productName,order.toString(),productCategories);
        PageInfo<CustomerProduct> pageInfo = new PageInfo<CustomerProduct>(list);
        return new DhPageInfo<CustomerProduct>(pageInfo, list);
    }

    /**
     * 产品分析
     * @param dateType
     * @return
     */
    @Override
    public ProductAnalyseVO selectProductAnalyse(String dateType) {
        UserAccount userAccount = (UserAccount) SecurityUtils.getSubject().getPrincipal();//当前登录人信息
        ProductAnalyseVO resultVo =new ProductAnalyseVO();
        ProductAnalyseVO vo;
        Integer dateUnit = getDateUnit(dateType);
        String startDate;
        String endDate;
        SimpleDateFormat f =new  SimpleDateFormat("yyyyMM");
        SimpleDateFormat ddFormat =new  SimpleDateFormat("yyyyMMdd");
        DateTimeFormatter fmt = DateTimeFormatter.ofPattern("yyyyMMdd");
        if (dateUnit == 7){//近三月
            Date date=new Date();
            String time=f.format(date);
            //上两个月的年份
            Integer year =Integer.valueOf(LocalDate.now().minusMonths(2).toString().substring(0,4));
            //上两个月月份
            String topMonth =LocalDate.now().minusMonths(2).toString().substring(5,7);
            startDate =year+""+topMonth+"01";
            endDate = LocalDate.now().toString().replaceAll("-","");
            //会员产品数量和额度
            vo = finishOrderDBservice.queryFinishProductCountAndPrice(dateUnit,userAccount.getAccountId(),1,startDate,endDate);
//            vo = finishOrderDBservice.selectProductCountAndPrice(dateUnit,userAccount.getAccountId(),1,startDate,endDate);
            resultVo.setVipProductProductCount(vo.getVipProductProductCount());
            resultVo.setVipProductCount(vo.getVipProductCount());
            //非会员产品数量和额度
            vo = finishOrderDBservice.queryFinishProductCountAndPrice(dateUnit,userAccount.getAccountId(),2,startDate,endDate);
            resultVo.setProductProductCount(vo.getProductProductCount());
            resultVo.setProductCount(vo.getProductCount());
            endDate = YearWeeksUtil.getMonthEnd(year,Integer.valueOf(topMonth)).replaceAll("-","");
            List<String> dateList =new ArrayList<>();
            for (int i=0;i<3 && (Integer.valueOf(endDate) < Integer.valueOf(LocalDate.now().toString().replaceAll("-","")) || Integer.valueOf(startDate) <Integer.valueOf(LocalDate.now().toString().replaceAll("-","")));i++){
                //会员产品
                List<String> str= finishOrderDBservice.selectVipProductCountList(dateUnit,userAccount.getAccountId(),startDate,endDate);
                resultVo.getVipProductList().add(str.get(0));
                //非会员产品
                str = finishOrderDBservice.selectProductCountList(dateUnit,userAccount.getAccountId(),startDate,endDate);
                resultVo.getProductList().add(str.get(0));
                //产品额度
                if (Integer.valueOf(endDate) > Integer.valueOf(LocalDate.now().toString().replaceAll("-",""))){
                    endDate =LocalDate.now().toString().replaceAll("-","");
                }
                dateList.add(startDate +" 至 "+endDate);
                //下个月1号
                startDate = LocalDate.parse(startDate, fmt).plusMonths(1).toString().replaceAll("-","").substring(0,6)+"01";
                endDate = YearWeeksUtil.getMonthEnd(Integer.valueOf(startDate.substring(0,4)),Integer.valueOf(startDate.substring(4,6))).replaceAll("-","");
            }
            //每个节点的开始日期和结束日期
            resultVo.setDateList(dateList);
        }else if (dateUnit == 5){ //上月
            Date date=new Date();
            SimpleDateFormat mmFormat =new  SimpleDateFormat("yyyyMM");
            String time=f.format(date);
            //上一个月的年份
            Integer year =Integer.valueOf(LocalDate.now().minusMonths(1).toString().substring(0,4));
            //上一个月月份
            String topMonth =LocalDate.now().minusMonths(1).toString().substring(5,7);
            startDate = year+""+topMonth+"01";
            LocalDate localDate=LocalDate.parse(startDate, fmt);
            endDate = YearWeeksUtil.getMonthEnd(year,Integer.valueOf(topMonth)).replaceAll("-","");
            //会员产品数量和额度
            vo = finishOrderDBservice.queryFinishProductCountAndPrice(dateUnit,userAccount.getAccountId(),1,startDate,endDate);
            resultVo.setVipProductProductCount(vo.getVipProductProductCount());
            resultVo.setVipProductCount(vo.getVipProductCount());
            vo = finishOrderDBservice.queryFinishProductCountAndPrice(dateUnit,userAccount.getAccountId(),2,startDate,endDate);
            resultVo.setProductProductCount(vo.getProductProductCount());
            resultVo.setProductCount(vo.getProductCount());

            endDate = localDate.plusDays(6).toString().replaceAll("-","");
            List<String> dateList =new ArrayList<>();
            //上月最大日期
            Integer maxDate =Integer.valueOf(YearWeeksUtil.getMonthEnd(year,Integer.valueOf(topMonth)).replaceAll("-",""));
            for (int i=0;i<5 && (Integer.valueOf(endDate) < maxDate || Integer.valueOf(startDate) <maxDate);i++){
                if (Integer.valueOf(endDate) > maxDate){
                    endDate = maxDate.toString();
                }
                //会员产品
                List<String> str= finishOrderDBservice.selectVipProductCountList(dateUnit,userAccount.getAccountId(),startDate,endDate);
                resultVo.getVipProductList().add(str.get(0));
                //非会员产品
                str = finishOrderDBservice.selectProductCountList(dateUnit,userAccount.getAccountId(),startDate,endDate);
                resultVo.getProductList().add(str.get(0));
                if (Integer.valueOf(endDate) > maxDate){
                    endDate =maxDate.toString();
                }
                dateList.add(startDate +" 至 "+endDate);
                startDate = LocalDate.parse(startDate, fmt).plusDays(7).toString().replaceAll("-","");
                endDate = LocalDate.parse(endDate, fmt).plusDays(7).toString().replaceAll("-","");
            }
            //每个节点的开始日期和结束日期
            resultVo.setDateList(dateList);

            //较上月比较
            year =Integer.valueOf(LocalDate.now().minusMonths(2).toString().substring(0,4));
            topMonth =LocalDate.now().minusMonths(2).toString().substring(5,7);
            startDate = year+""+topMonth+"01";
            localDate=LocalDate.parse(startDate, fmt);
            endDate = YearWeeksUtil.getMonthEnd(year,Integer.valueOf(topMonth)).replaceAll("-","");
            vo = finishOrderDBservice.queryFinishProductCountAndPrice(dateUnit,userAccount.getAccountId(),1,startDate,endDate);
            //较上月会员产品数量
            resultVo.setVipProductCompare(countRatio(resultVo.getVipProductCount(),vo.getVipProductCount()));
            //较上月会员产品销售额度
            resultVo.setVipProductProductCompare(countRatio(resultVo.getVipProductProductCount(),vo.getVipProductProductCount()));
            vo = finishOrderDBservice.queryFinishProductCountAndPrice(dateUnit,userAccount.getAccountId(),2,startDate,endDate);
            //较上月非会员产品数量
            resultVo.setProductCompare(countRatio(resultVo.getProductCount(),vo.getProductCount()));
            //较上月会员产品销售额度
            resultVo.setProductProductCompare(countRatio(resultVo.getProductProductCount(),vo.getProductProductCount()));
        }else if (dateUnit == 2){ //本月
            Date date=new Date();
            String time=f.format(date);
            //上一个月的年份
            Integer year =Integer.valueOf(LocalDate.now().minusMonths(1).toString().substring(0,4));
            //上一个月月份
            String month =LocalDate.now().toString().substring(5,7);
            startDate = time+"01";
            LocalDate localDate=LocalDate.parse(startDate, fmt);
            endDate = YearWeeksUtil.getMonthEnd(year,Integer.valueOf(month)).replaceAll("-","");
            //会员产品数量和额度
            vo = finishOrderDBservice.queryFinishProductCountAndPrice(dateUnit,userAccount.getAccountId(),1,startDate,endDate);
            resultVo.setVipProductProductCount(vo.getVipProductProductCount());
            resultVo.setVipProductCount(vo.getVipProductCount());
            vo = finishOrderDBservice.queryFinishProductCountAndPrice(dateUnit,userAccount.getAccountId(),2,startDate,endDate);
            resultVo.setProductProductCount(vo.getProductProductCount());
            resultVo.setProductCount(vo.getProductCount());
            endDate = localDate.plusDays(6).toString().replaceAll("-","");
            List<String> dateList =new ArrayList<>();
            //最大日期
            Integer maxDate =Integer.valueOf(ddFormat.format(date).replaceAll("-",""));
            for (int i=0;i<5 && (Integer.valueOf(endDate) <= maxDate || Integer.valueOf(startDate) <= maxDate);i++){
                //会员产品
                List<String> str= finishOrderDBservice.selectVipProductCountList(dateUnit,userAccount.getAccountId(),startDate,endDate);
                resultVo.getVipProductList().add(str.get(0));
                //非会员产品
                str = finishOrderDBservice.selectProductCountList(dateUnit,userAccount.getAccountId(),startDate,endDate);
                resultVo.getProductList().add(str.get(0));
                if (Integer.valueOf(endDate) > maxDate){
                    endDate =maxDate.toString();
                }
                dateList.add(startDate +" 至 "+endDate);
                startDate = LocalDate.parse(startDate, fmt).plusDays(7).toString().replaceAll("-","");
                endDate = LocalDate.parse(endDate, fmt).plusDays(7).toString().replaceAll("-","");
            }
            //每个节点的开始日期和结束日期
            resultVo.setDateList(dateList);

            //上一个月月份
            String topMonth =LocalDate.now().minusMonths(1).toString().substring(5,7);
            //较上月比较
            startDate = year+""+topMonth+"01";
            localDate=LocalDate.parse(startDate, fmt);
            endDate = YearWeeksUtil.getMonthEnd(year,Integer.valueOf(topMonth)).replaceAll("-","");
            vo = finishOrderDBservice.queryFinishProductCountAndPrice(dateUnit,userAccount.getAccountId(),1,startDate,endDate);
            //较上月会员产品数量
            resultVo.setVipProductCompare(countRatio(resultVo.getVipProductCount(),vo.getVipProductCount()));
            //较上月会员产品销售额度
            resultVo.setVipProductProductCompare(countRatio(resultVo.getVipProductProductCount(),vo.getVipProductProductCount()));
            vo = finishOrderDBservice.queryFinishProductCountAndPrice(dateUnit,userAccount.getAccountId(),2,startDate,endDate);
            //较上月非会员产品数量
            resultVo.setProductCompare(countRatio(resultVo.getProductCount(),vo.getProductCount()));
            //较上月会员产品销售额度
            resultVo.setProductProductCompare(countRatio(resultVo.getProductProductCount(),vo.getProductProductCount()));
        }else {
            //会员产品
            resultVo.setVipProductList(finishOrderDBservice.selectVipProductCountList(dateUnit,userAccount.getAccountId(),null,null));
            //非会员产品
            resultVo.setProductList(finishOrderDBservice.selectProductCountList(dateUnit,userAccount.getAccountId(),null,null));
            //会员产品数量和额度
            vo = finishOrderDBservice.queryFinishProductCountAndPrice(dateUnit,userAccount.getAccountId(),1,null,null);
            resultVo.setVipProductProductCount(vo.getVipProductProductCount());
            resultVo.setVipProductCount(vo.getVipProductCount());
            vo = finishOrderDBservice.queryFinishProductCountAndPrice(dateUnit,userAccount.getAccountId(),2,null,null);
            resultVo.setProductProductCount(vo.getProductProductCount());
            resultVo.setProductCount(vo.getProductCount());
        }
        return resultVo;
    }


    @Override
    public ProductAnalyseVO selectProductAnalyse(String dateType, String accountId) {
        ProductAnalyseVO resultVo =new ProductAnalyseVO();
        ProductAnalyseVO vo;
        Integer dateUnit = getDateUnit(dateType);
        String startDate;
        String endDate;
        SimpleDateFormat f =new  SimpleDateFormat("yyyyMM");
        SimpleDateFormat ddFormat =new  SimpleDateFormat("yyyyMMdd");
        DateTimeFormatter fmt = DateTimeFormatter.ofPattern("yyyyMMdd");
        if (dateUnit == 7){//近三月
            Date date=new Date();
            String time=f.format(date);
            //上两个月的年份
            Integer year =Integer.valueOf(LocalDate.now().minusMonths(2).toString().substring(0,4));
            //上两个月月份
            String topMonth =LocalDate.now().minusMonths(2).toString().substring(5,7);
            startDate =year+""+topMonth+"01";
            endDate = LocalDate.now().toString().replaceAll("-","");
            //会员产品数量和额度
            vo = finishOrderDBservice.selectProductCountAndPrice(dateUnit,accountId,1,startDate,endDate);
            resultVo.setVipProductProductCount(vo.getVipProductProductCount());
            resultVo.setVipProductCount(vo.getVipProductCount());
            vo = finishOrderDBservice.selectProductCountAndPrice(dateUnit,accountId,2,startDate,endDate);
            resultVo.setProductProductCount(vo.getProductProductCount());
            resultVo.setProductCount(vo.getProductCount());
            endDate = YearWeeksUtil.getMonthEnd(year,Integer.valueOf(topMonth)).replaceAll("-","");
            List<String> dateList =new ArrayList<>();
            for (int i=0;i<3 && (Integer.valueOf(endDate) < Integer.valueOf(LocalDate.now().toString().replaceAll("-","")) || Integer.valueOf(startDate) <Integer.valueOf(LocalDate.now().toString().replaceAll("-","")));i++){
                //会员产品
                List<String> str= finishOrderDBservice.selectVipProductCountList(dateUnit,accountId,startDate,endDate);
                resultVo.getVipProductList().add(str.get(0));
                //非会员产品
                str = finishOrderDBservice.selectProductCountList(dateUnit,accountId,startDate,endDate);
                resultVo.getProductList().add(str.get(0));
                //产品额度
                if (Integer.valueOf(endDate) > Integer.valueOf(LocalDate.now().toString().replaceAll("-",""))){
                    endDate =LocalDate.now().toString().replaceAll("-","");
                }
                dateList.add(startDate +" 至 "+endDate);
                //下个月1号
                startDate = LocalDate.parse(startDate, fmt).plusMonths(1).toString().replaceAll("-","").substring(0,6)+"01";
                endDate = YearWeeksUtil.getMonthEnd(Integer.valueOf(startDate.substring(0,4)),Integer.valueOf(startDate.substring(4,6))).replaceAll("-","");
            }
            //每个节点的开始日期和结束日期
            resultVo.setDateList(dateList);
        }else if (dateUnit == 5){ //上月
            Date date=new Date();
            SimpleDateFormat mmFormat =new  SimpleDateFormat("yyyyMM");
            String time=f.format(date);
            //上一个月的年份
            Integer year =Integer.valueOf(LocalDate.now().minusMonths(1).toString().substring(0,4));
            //上一个月月份
            String topMonth =LocalDate.now().minusMonths(1).toString().substring(5,7);
            startDate = year+""+topMonth+"01";
            LocalDate localDate=LocalDate.parse(startDate, fmt);
            endDate = YearWeeksUtil.getMonthEnd(year,Integer.valueOf(topMonth)).replaceAll("-","");
            //会员产品数量和额度
            vo = finishOrderDBservice.selectProductCountAndPrice(dateUnit,accountId,1,startDate,endDate);
            resultVo.setVipProductProductCount(vo.getVipProductProductCount());
            resultVo.setVipProductCount(vo.getVipProductCount());
            vo = finishOrderDBservice.selectProductCountAndPrice(dateUnit,accountId,2,startDate,endDate);
            resultVo.setProductProductCount(vo.getProductProductCount());
            resultVo.setProductCount(vo.getProductCount());

            endDate = localDate.plusDays(6).toString().replaceAll("-","");
            List<String> dateList =new ArrayList<>();
            //上月最大日期
            Integer maxDate =Integer.valueOf(YearWeeksUtil.getMonthEnd(year,Integer.valueOf(topMonth)).replaceAll("-",""));
            for (int i=0;i<5 && (Integer.valueOf(endDate) < maxDate || Integer.valueOf(startDate) <maxDate);i++){
                if (Integer.valueOf(endDate) > maxDate){
                    endDate = maxDate.toString();
                }
                //会员产品
                List<String> str= finishOrderDBservice.selectVipProductCountList(dateUnit,accountId,startDate,endDate);
                resultVo.getVipProductList().add(str.get(0));
                //非会员产品
                str = finishOrderDBservice.selectProductCountList(dateUnit,accountId,startDate,endDate);
                resultVo.getProductList().add(str.get(0));
                if (Integer.valueOf(endDate) > maxDate){
                    endDate =maxDate.toString();
                }
                dateList.add(startDate +" 至 "+endDate);
                startDate = LocalDate.parse(startDate, fmt).plusDays(7).toString().replaceAll("-","");
                endDate = LocalDate.parse(endDate, fmt).plusDays(7).toString().replaceAll("-","");
            }
            //每个节点的开始日期和结束日期
            resultVo.setDateList(dateList);

            //较上月比较
            year =Integer.valueOf(LocalDate.now().minusMonths(2).toString().substring(0,4));
            topMonth =LocalDate.now().minusMonths(2).toString().substring(5,7);
            startDate = year+""+topMonth+"01";
            localDate=LocalDate.parse(startDate, fmt);
            endDate = YearWeeksUtil.getMonthEnd(year,Integer.valueOf(topMonth)).replaceAll("-","");
            vo = finishOrderDBservice.selectProductCountAndPrice(dateUnit,accountId,1,startDate,endDate);
            //较上月会员产品数量
            resultVo.setVipProductCompare(countRatio(resultVo.getVipProductCount(),vo.getVipProductCount()));
            //较上月会员产品销售额度
            resultVo.setVipProductProductCompare(countRatio(resultVo.getVipProductProductCount(),vo.getVipProductProductCount()));
            vo = finishOrderDBservice.selectProductCountAndPrice(dateUnit,accountId,2,startDate,endDate);
            //较上月非会员产品数量
            resultVo.setProductCompare(countRatio(resultVo.getProductCount(),vo.getProductCount()));
            //较上月会员产品销售额度
            resultVo.setProductProductCompare(countRatio(resultVo.getProductProductCount(),vo.getProductProductCount()));
        }else if (dateUnit == 2){ //本月
            Date date=new Date();
            String time=f.format(date);
            //上一个月的年份
            Integer year =Integer.valueOf(LocalDate.now().minusMonths(1).toString().substring(0,4));
            //上一个月月份
            String month =LocalDate.now().toString().substring(5,7);
            startDate = time+"01";
            LocalDate localDate=LocalDate.parse(startDate, fmt);
            endDate = YearWeeksUtil.getMonthEnd(year,Integer.valueOf(month)).replaceAll("-","");
            //会员产品数量和额度
            vo = finishOrderDBservice.selectProductCountAndPrice(dateUnit,accountId,1,startDate,endDate);
            resultVo.setVipProductProductCount(vo.getVipProductProductCount());
            resultVo.setVipProductCount(vo.getVipProductCount());
            vo = finishOrderDBservice.selectProductCountAndPrice(dateUnit,accountId,2,startDate,endDate);
            resultVo.setProductProductCount(vo.getProductProductCount());
            resultVo.setProductCount(vo.getProductCount());
            endDate = localDate.plusDays(6).toString().replaceAll("-","");
            List<String> dateList =new ArrayList<>();
            //最大日期
            Integer maxDate =Integer.valueOf(ddFormat.format(date).replaceAll("-",""));
            for (int i=0;i<5 && (Integer.valueOf(endDate) <= maxDate || Integer.valueOf(startDate) <= maxDate);i++){
                //会员产品
                List<String> str= finishOrderDBservice.selectVipProductCountList(dateUnit,accountId,startDate,endDate);
                resultVo.getVipProductList().add(str.get(0));
                //非会员产品
                str = finishOrderDBservice.selectProductCountList(dateUnit,accountId,startDate,endDate);
                resultVo.getProductList().add(str.get(0));
                if (Integer.valueOf(endDate) > maxDate){
                    endDate =maxDate.toString();
                }
                dateList.add(startDate +" 至 "+endDate);
                startDate = LocalDate.parse(startDate, fmt).plusDays(7).toString().replaceAll("-","");
                endDate = LocalDate.parse(endDate, fmt).plusDays(7).toString().replaceAll("-","");
            }
            //每个节点的开始日期和结束日期
            resultVo.setDateList(dateList);

            //上一个月月份
            String topMonth =LocalDate.now().minusMonths(1).toString().substring(5,7);
            //较上月比较
            startDate = year+""+topMonth+"01";
            localDate=LocalDate.parse(startDate, fmt);
            endDate = YearWeeksUtil.getMonthEnd(year,Integer.valueOf(topMonth)).replaceAll("-","");
            vo = finishOrderDBservice.selectProductCountAndPrice(dateUnit,accountId,1,startDate,endDate);
            //较上月会员产品数量
            resultVo.setVipProductCompare(countRatio(resultVo.getVipProductCount(),vo.getVipProductCount()));
            //较上月会员产品销售额度
            resultVo.setVipProductProductCompare(countRatio(resultVo.getVipProductProductCount(),vo.getVipProductProductCount()));
            vo = finishOrderDBservice.selectProductCountAndPrice(dateUnit,accountId,2,startDate,endDate);
            //较上月非会员产品数量
            resultVo.setProductCompare(countRatio(resultVo.getProductCount(),vo.getProductCount()));
            //较上月会员产品销售额度
            resultVo.setProductProductCompare(countRatio(resultVo.getProductProductCount(),vo.getProductProductCount()));
        }else {
            //会员产品
            resultVo.setVipProductList(finishOrderDBservice.selectVipProductCountList(dateUnit,accountId,null,null));
            //非会员产品
            resultVo.setProductList(finishOrderDBservice.selectProductCountList(dateUnit,accountId,null,null));
            //会员产品数量和额度
            vo = finishOrderDBservice.selectProductCountAndPrice(dateUnit,accountId,1,null,null);
            resultVo.setVipProductProductCount(vo.getVipProductProductCount());
            resultVo.setVipProductCount(vo.getVipProductCount());
            vo = finishOrderDBservice.selectProductCountAndPrice(dateUnit,accountId,2,null,null);
            resultVo.setProductProductCount(vo.getProductProductCount());
            resultVo.setProductCount(vo.getProductCount());
        }
        return resultVo;
    }


    @Override
    public boolean addProductAnalyseToRedis() {
        List<UserAccount> allAccountList = userAccountDbService.getAllAccountList();
        List<String> dateTypeList = Arrays.asList("thisMonth","topMonth","threeMonth","thisQuarter","thisYear");

        if (CollectionUtils.isEmpty(allAccountList)){
            return false;
        }

        for (UserAccount userAccount : allAccountList) {
            for (String dateType : dateTypeList) {
                try {
                    ProductAnalyseVO resultVo = selectProductAnalyse(dateType, userAccount.getAccountId());
                    boolean addredis = addProductAnalyseToRedis(dateType, userAccount.getAccountId(), resultVo);
                } catch (Exception e) {
                    log.error("CustomerProductServiceImpl->addProductAnalyseToRedis,accountId:{},dateType:{},error:{}"
                            ,userAccount.getAccountId(),dateType,e);
                }
            }
        }

        return true;
    }


    private boolean addProductAnalyseToRedis(String dateType, String accountId, ProductAnalyseVO resultVo) {
        boolean flag = ValueRMapper.setRedisObject(redisTemplate, getProductAnalyseKey(dateType,accountId), resultVo);
        return flag;
    }


    private String getProductAnalyseKey(String dateType,String accountId) {
        return RedisPrefix.PRODUCT_ANALYSE + accountId + "_" + dateType;
    }


    /**
     * 计算本月业绩比较上月业绩比例
     * @param l1 上月业绩
     * @param l2 本月业绩
     * @return
     */
    public BigDecimal countRatio(String l1, String l2){
        BigDecimal bigl1 = new BigDecimal(l1);
        BigDecimal bigl2 = new BigDecimal(l2);
        //两个月都为0
        if(l2.equals(l1)){
            return new BigDecimal("0");
        }
        //上月为0 本月不为0
        if (!new BigDecimal("0").equals(bigl2.toString()) && new BigDecimal("0").toString().equals(bigl1.toString())){
            return bigl2.setScale(1,BigDecimal.ROUND_HALF_UP);
        }
        BigDecimal big = bigl1.subtract(bigl2);
        big = big.divide(bigl1,1,BigDecimal.ROUND_HALF_UP);
        return big;
    }

    /**
     * 订单完成的产品列表统计getContactReportLine
     * @param pageIndex
     * @param pageSize
     * @param sortName
     * @param sortOrder
     * @param dateType
     * @return
     */
    @Override
    public DhPageInfo<AnalyseFinishOrderProductVO> selectFinishOrderProductList(Integer pageIndex, Integer pageSize, String sortName, String sortOrder, String dateType) {
        if (pageIndex != null && pageSize != null) {
            PageHelper.startPage(pageIndex, pageSize);
        }

        //排序
        StringBuilder order = new StringBuilder();
        if(!StringUtils.isBlank(sortName)&&!StringUtils.isBlank(sortOrder)){
            order.append(sortName).append(" ").append(sortOrder);
//            switch(sortName){
//                case "productPriceCount":
//                {
//                    order.append("productPriceCount ").append(sortOrder);//销售额
//                }
//                break;
//                case "ratio":
//                {
//                    order.append("productPriceCount ").append(sortOrder);//占比，也用销售额排序，销售额大占比肯定高
//                }
//                break;
//                default:
//                    break;
//            }
        }
        Integer dateUnit = getDateUnit(dateType);
        UserAccount userAccount = (UserAccount) SecurityUtils.getSubject().getPrincipal();//当前登录人信息
        List<AnalyseFinishOrderProductVO> performanceList = finishOrderDBservice.getPerformanceList(dateUnit,order,userAccount.getAccountId());
        PageInfo<AnalyseFinishOrderProductVO> pageInfo = new PageInfo<AnalyseFinishOrderProductVO>(performanceList);
//        List<AnalyseFinishOrderProductVO> customerProductVOList = finishOrderDBservice.selectAnalyseFinishOrderProductList(dateUnit,order,userAccount.getAccountId());
//        BigDecimal big = finishOrderDBservice.getUserProductPriceCount(dateUnit,userAccount.getAccountId());
//        BigDecimal numBig = new BigDecimal("100");
//        for (int i=0;i<customerProductVOList.size();i++){
//            numBig = customerProductVOList.get(i).getProductPriceCount().divide(big,4);
//            customerProductVOList.get(i).setRatio(String.valueOf(numBig.multiply(new BigDecimal("100"))));
//        }
        return new DhPageInfo<AnalyseFinishOrderProductVO>(pageInfo, performanceList);
    }

    /**
     * 日期类型(全部/本周/本月/本年度)
     * @Author chaifuyou
     * @Date  2021/4/15 16:12
     * @param dateType -(all:全部; thisWeek:本周; thisMonth:本月; thisYear:本年；thisToday:今天)
     * @return {@link {java.lang.Integer}}
     */
    private Integer getDateUnit(String dateType) {
        Integer dateUnit = 0;
        if (!StringUtils.isBlank(dateType)) {
            if ("thisWeek".equals(dateType)) {
                //本周
                dateUnit = 1;
            }
            if ("topMonth".equals(dateType)) {
                //上月
                dateUnit = 5;
            }
            if ("thisMonth".equals(dateType)) {
                //本月
                dateUnit = 2;
            }
            if ("thisYear".equals(dateType)) {
                //本年
                dateUnit = 3;
            }
            if ("thisToday".equals(dateType)) {
                //今天
                dateUnit = 4;
            }
            if ("thisQuarter".equals(dateType)) {
                //本季度
                dateUnit = 6;
            }
            if ("threeMonth".equals(dateType)) {
                //近三月
                dateUnit = 7;
            }
        }
        return dateUnit;
    }

}
